package com.criticalbotch.enjinapi;

import java.util.HashMap;

import org.json.JSONObject;

import com.google.gson.Gson;

public class UserManager {
	
	private HashMap<Integer, EnjinUser>users = new HashMap<Integer, EnjinUser>();
	
	public void usersFromJSON(String JSON)
	{
		try
		{
			JSONObject job = new JSONObject(JSON);
			usersFromJSON(job);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void usersFromJSON(JSONObject json)
	{
		for(Object id : json.keySet())
		{
			Gson gson = new Gson();
			try
			{
				String ID = (String)id;
				JSONObject job = json.getJSONObject(ID);
				EnjinUser user = gson.fromJson(job.toString(), EnjinUser.class);
				addUser(Integer.parseInt(ID), user);
				
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	public void addUser(int id, EnjinUser user)
	{
		user.setID(id);
		users.put(id, user);
	}
	
	public void addUser(int id, JSONObject JSON)
	{		
		String json = ""+JSON;
		addUser(id, json);
	}
	
	public void addUser(int id, String JSON)
	{
		Gson gson = new Gson();
		
		EnjinUser user = gson.fromJson(JSON, EnjinUser.class);
		
		addUser(id, user);
	}
	
	public void addUsers(String JSON)
	{
		usersFromJSON(JSON);
	}
	
	public void addUsers(JSONObject JSON)
	{
		usersFromJSON(JSON);
	}
	
	EnjinUser getUser(int id)
	{
		return users.get(id);
	}
	
	EnjinUser getUser(String username)
	{
		EnjinUser ret = null;
		for(int i : users.keySet())
		{
			EnjinUser user = users.get(i);
			if(username.equals(user.getUsername()))
			{
				ret = user;
				break;
			}			
		}
		
		return ret;
	}

}
